package main

// $ go mod init github.com/zhangxi/grpc_greeter_client
// $ ==> go mod init grpc_greeter_client
// $ go mod tidy  #==> 下载项目中引入的第三方包, 因为这里是直接从 "/server/greeter/proto/" 目录复制过来的, 我们需要 "$ go mod tidy" 获取依赖包,
// $ protoc --go_out=plugins=grpc:./ *.proto    // 使用 protoc-gen-go.exe
// $ 而不再是 protoc --go_out=./ order.proto

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"grpc_greeter_client/proto/greeterService"
	"strconv"

	// "github.com/hashicorp/consul"
	"github.com/hashicorp/consul/api"
)

func main() {

	// 发现服务,
	// 1.初始化 consul 配置,
	consulConfig := api.DefaultConfig()
	consulConfig.Address = "127.0.0.1:8500"
	// 2.获取 consul 操作对象,
	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		fmt.Println("consul api.NewClient() err:", err)
		return
	}
	// 3.获取地址,
	// serviceEntry, queryMeta, err := consulClient.Health().Service("HelloService", "test", false, &api.QueryOptions{})
	serviceEntry, queryMeta, err := consulClient.Health().Service("HelloService", "test", false, nil)
	if err != nil {
		fmt.Println("consul consulClient.Health().Service() err:", err)
		fmt.Println(queryMeta.LastContentHash)
		return
	}
	fmt.Println(serviceEntry[0].Service.Address, serviceEntry[0].Service.Port)
	// fmt.Println(queryMeta)
	// 4.和 grpc 服务建立连接,
	address := serviceEntry[0].Service.Address + ":" + strconv.Itoa(serviceEntry[0].Service.Port)

	// 1.建立 tcp 连接,
	// conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		fmt.Println("grpc.Dial() err:", err)
		return
	}
	// 2.注册客户端,
	client := greeterService.NewGreeterClient(conn)
	// 3.调用远程函数,
	resp, err := client.SayHello(context.Background(), &greeterService.HelloReq{Name: "zhangsan"})
	if err != nil {
		fmt.Println("client.SayHello() err:", err)
		return
	}
	// 4.获取微服务返回的数据,
	fmt.Printf("%#v\n", resp)
	fmt.Println(resp.GetMessage())
}
